package com.example.myapplication.frags;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.route.BikingRoutePlanOption;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.search.share.ShareUrlSearch;
import com.example.myapplication.R;
import com.example.myapplication.data.MessageEvent;
import com.example.myapplication.utils.baiduUtil.overlayutil.BikingRouteOverlay;
import com.example.myapplication.utils.baiduUtil.overlayutil.WalkingRouteOverlay;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 校园地图模块,调用百度地图
 * 功能：搜索地标、规划路线、定位当前
 */
public class SchoolMap_Fragment extends Fragment {

    private static final String TAG = "SchoolMap_Fragment";

    // 常用的搜索地点，比如 食堂 宿舍 教学楼
    List<String> usualLocations = new ArrayList<>();

    List<Integer> range = new ArrayList<>();
    // 百度地图提供的类
    MapView mapVIew = null;
    BaiduMap mBaiduMap;
    LocationClient locationClient;
    // 用于搜索相关点
    PoiSearch poiSearch;
    // 搜索路径
    RoutePlanSearch mSearch = RoutePlanSearch.newInstance();
    // 当前我的位置
    LatLng curLocation;
    Integer curRange = 500;
    ShareUrlSearch mShareUrlSearch = ShareUrlSearch.newInstance();
    private boolean isNormalMap = false;

    public SchoolMap_Fragment() {
        // Required empty public constructor

    }

    public static SchoolMap_Fragment newInstance(String param1, String param2) {
        SchoolMap_Fragment fragment = new SchoolMap_Fragment();
        Bundle args = new Bundle();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
        // 可以改成 web 存取
        String[] arr = {"请选择", "食堂", "宿舍", "教学楼", "体育馆", "操场", "工程训练中心", "图书馆", "人文楼"};
        Integer[] range = {10, 50, 100, 200, 500, 1000};
        usualLocations.addAll(Arrays.asList(arr));
        this.range.addAll(Arrays.asList(range));

        // 不要动
        SDKInitializer.setAgreePrivacy(this.getContext().getApplicationContext(), true);
        SDKInitializer.initialize(this.getContext().getApplicationContext());
        SDKInitializer.setCoordType(CoordType.BD09LL);
        LocationClient.setAgreePrivacy(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_school_map, container, false);

        //-----------------------------设置下拉框以及事件---------------------------------
        Spinner spinner = root.findViewById(R.id.list_locations);
        spinner.setAdapter(new ArrayAdapter<String>(this.getContext(), androidx.appcompat.R.layout.support_simple_spinner_dropdown_item, usualLocations));

        Spinner spinner_range = root.findViewById(R.id.sp_range);
        spinner_range.setAdapter(new ArrayAdapter<Integer>(this.getContext(), androidx.appcompat.R.layout.support_simple_spinner_dropdown_item, this.range));
        spinner_range.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                curRange = (Integer) adapterView.getItemAtPosition(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        //下拉搜索位置，并显示
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == 0) {
                    return;
                }
                String itemAtPosition = (String) adapterView.getItemAtPosition(i);

                mBaiduMap.clear();
                //进行附近搜索
                poiSearch.searchNearby(new PoiNearbySearchOption().
                        location(curLocation).
                        keyword(itemAtPosition).
                        radius(curRange).
                        pageNum(0));
                int height = 0;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
                    height = getContext().getDisplay().getHeight();
                }
                Toast tos = Toast.makeText(getContext(), "搜索半径: " + curRange, Toast.LENGTH_SHORT);
                tos.setGravity(Gravity.TOP, 0, height / 5);
                tos.show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        //-----------------------------设置下拉框以及事件---------------------------------

        //-----------------------------设置地图对象--------------------------------------
        mapVIew = root.findViewById(R.id.bmapView);
        mBaiduMap = mapVIew.getMap();
        mBaiduMap.setMyLocationEnabled(true);
        poiSearch = PoiSearch.newInstance();

        //定位初始化
        try {
            locationClient = new LocationClient(this.getContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //-----------------------------设置地图对象--------------------------------------

        //通过LocationClientOption设置LocationClient相关参数
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(500);
        option.setIsNeedAddress(true);//接收详细信息
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.zoom(18.0f);
        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.id.btn_me);
        MyLocationConfiguration myLocationConfiguration =
                new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING,
                        true,
                        bitmapDescriptor,
                        0xAAFFFF88,
                        0xAAFFFF88
                );
        MyLocationConfiguration myLocationConfiguration2 =
                new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL,
                        true,
                        bitmapDescriptor,
                        0xAAFFFF88,
                        0xAAFFFF88
                );
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        mBaiduMap.setMyLocationConfiguration(myLocationConfiguration);
        mBaiduMap.setIndoorEnable(true);
        locationClient.setLocOption(option);

        MyLocationListener myLocationListener = new MyLocationListener();
        locationClient.registerLocationListener(myLocationListener);
        locationClient.start();

        //-----------------------------------设置路径搜索结果回调--------------------------------------
        mSearch.setOnGetRoutePlanResultListener(new OnGetRoutePlanResultListener() {
            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {
                //创建WalkingRouteOverlay实例
                WalkingRouteOverlay overlay = new WalkingRouteOverlay(mBaiduMap);
                if (walkingRouteResult.getRouteLines() == null) {
                    int height = 0;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
                        height = getContext().getDisplay().getHeight();
                    }
                    Toast tos = Toast.makeText(getContext(), "没有搜索到内容", Toast.LENGTH_SHORT);
                    tos.setGravity(Gravity.TOP, 0, height / 5);
                    tos.show();
                    return;
                }
                if (walkingRouteResult.getRouteLines().size() > 0) {
                    //获取路径规划数据,(以返回的第一条数据为例)
                    //为WalkingRouteOverlay实例设置路径数据
                    overlay.setData(walkingRouteResult.getRouteLines().get(0));
                    //在地图上绘制WalkingRouteOverlay
                    overlay.addToMap();
                }
            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

            }

            @Override
            public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

            }

            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {

            }

            @Override
            public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

            }

            @Override
            public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

            }
        });

        //-----------------------------设置兴趣点搜索结果回调---------------------------------
        poiSearch.setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() {
            @Override
            public void onGetPoiResult(PoiResult poiResult) {
                if (poiResult == null) {
                    return;
                }
                if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {
                    //定义Maker坐标点
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        poiResult.getAllPoi().forEach(poiInfo -> {
                            LatLng point = poiInfo.location;
                            BitmapDescriptor bitmap = BitmapDescriptorFactory
                                    .fromResource(R.drawable.location);
                            OverlayOptions option = new MarkerOptions().scaleX(0.1F).scaleY(0.1F).animateType(MarkerOptions.MarkerAnimateType.jump)
                                    .position(point)
                                    .icon(bitmap);

                            mBaiduMap.addOverlay(option);
                        });
                    }

                }
            }

            @Override
            public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

            }

            @Override
            public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    poiDetailSearchResult.getPoiDetailInfoList().forEach(poiDetailInfo -> {

                        Log.d(TAG, "onGetPoiDetailResult: " + poiDetailInfo.detailUrl);
                        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());

                        builder.setTitle("将打开浏览器显示地标信息？").setIcon(R.drawable.location)
                                .setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
                        builder.setPositiveButton("确定", (dialog, which) -> {
                            WebView webView = new WebView(getContext());
                            webView.loadUrl(poiDetailInfo.detailUrl);
                            //do something
                        });

                        AlertDialog dialog = builder.show();
                        Button btnPos =dialog.getButton(DialogInterface.BUTTON_POSITIVE);
                        Button btnNeg = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
                        btnPos.setTextColor(Color.RED);
                        btnNeg.setTextColor(Color.RED);
                    });
                }
            }

            @Override
            public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

            }
        });

        root.findViewById(R.id.btn_search_walk).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final EditText inputServer = new EditText(view.getContext());
                AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                builder.setTitle("步行路径规划").setIcon(R.drawable.location).setView(inputServer)
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String destiName = inputServer.getText().toString();
                        //do something..
                        PlanNode desNode = PlanNode.withCityNameAndPlaceName("南昌", destiName.toString());
                        PlanNode startNode = PlanNode.withLocation(curLocation);
                        mSearch.walkingSearch(new WalkingRoutePlanOption().from(startNode).to(desNode));
                    }
                });
                AlertDialog dialog = builder.show();
                Button btnPos =dialog.getButton(DialogInterface.BUTTON_POSITIVE);
                Button btnNeg = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
                btnPos.setTextColor(Color.RED);
                btnNeg.setTextColor(Color.RED);
            }
        });
        root.findViewById(R.id.btn_erase_map).setOnClickListener(view -> {
            mBaiduMap.clear();
        });

        root.findViewById(R.id.btn_switch_mode).setOnClickListener(view -> {
            if (!isNormalMap) {

                mBaiduMap.setMyLocationConfiguration(myLocationConfiguration2);
                isNormalMap = true;

            } else {
                mBaiduMap.setMyLocationConfiguration(myLocationConfiguration);
                isNormalMap = false;
            }
        });
        mBaiduMap.setOnMarkerClickListener(marker -> {
            PlanNode desNode = PlanNode.withLocation(marker.getPosition());
            PlanNode startNode = PlanNode.withLocation(curLocation);
            mSearch.walkingSearch(new WalkingRoutePlanOption().from(startNode).to(desNode));
            return true;
        });
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                BitmapDescriptor bitmap = BitmapDescriptorFactory
                        .fromResource(R.drawable.ques);
                OverlayOptions option = new MarkerOptions().scaleX(0.1F).scaleY(0.1F).
                        animateType(MarkerOptions.MarkerAnimateType.grow)
                        .position(latLng)
                        .icon(bitmap);

                mBaiduMap.addOverlay(option);
            }

            @Override
            public void onMapPoiClick(MapPoi mapPoi) {
                Log.d(TAG, "onMapPoiClick: ");
                poiSearch.searchPoiDetail(new PoiDetailSearchOption().poiUids(mapPoi.getUid()));
            }
        });
        root.findViewById(R.id.btn_show_help).setOnClickListener(view -> {
            AlertDialog.Builder builder2 = new AlertDialog.Builder(getContext());
            builder2.setView(R.layout.map_help);
            builder2.setTitle("帮助").setIcon(R.drawable.help)
                    .setPositiveButton("确定", (dialog, which) -> {
                        //do something
                    }).show();
        });
        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        //在Fragment执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mapVIew.onResume();
        locationClient.start();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在<span style="font-family: 微软雅黑, 'Microsoft YaHei', sans-serif;">Fragment</span>执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mapVIew.onPause();
        locationClient.stop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //在Fragment执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mapVIew.onDestroy();
        locationClient.stop();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) {
            locationClient.stop();
        } else {
            locationClient.start();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        Log.d("MAP", "onMessageEvent: " + event.getMessage());

    }

    // 不断监听位置变化
    @SuppressLint("SuspiciousIndentation")
    class MyLocationListener extends BDAbstractLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mapVIew == null) {
                return;
            }
            curLocation = new LatLng(location.getLatitude(), location.getLongitude());
            Log.d(TAG, "onReceiveLocation: " + location.getAddrStr());
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(location.getDirection()).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);

        }
    }

}